package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.WorkerCertificationAuditMapper;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.mapper.WorkerCertificationAuditMapper;
import com.jzo2o.customer.mapper.WorkerCertificationMapper;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.domain.WorkerCertificationAudit;
import com.jzo2o.customer.model.dto.WorkerCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.WorkerCertificationAuditResDTO;
import com.jzo2o.customer.service.IWorkerCertificationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务人员认证信息表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-06
 */
@Service
public class WorkerCertificationServiceImpl extends ServiceImpl<WorkerCertificationMapper, WorkerCertification> implements IWorkerCertificationService {

    @Autowired
    WorkerCertificationAuditMapper workerCertificationAuditMapper;


    /**
     * 根据服务人员id更新
     *
     * @param workerCertificationUpdateDTO 服务人员认证更新模型
     */
    @Override
    public void updateById(WorkerCertificationUpdateDTO workerCertificationUpdateDTO) {
        LambdaUpdateWrapper<WorkerCertification> updateWrapper = Wrappers.<WorkerCertification>lambdaUpdate()
                .eq(WorkerCertification::getId, workerCertificationUpdateDTO.getId())
                .set(WorkerCertification::getCertificationStatus, workerCertificationUpdateDTO.getCertificationStatus())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getName()), WorkerCertification::getName, workerCertificationUpdateDTO.getName())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getIdCardNo()), WorkerCertification::getIdCardNo, workerCertificationUpdateDTO.getIdCardNo())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getFrontImg()), WorkerCertification::getFrontImg, workerCertificationUpdateDTO.getFrontImg())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getBackImg()), WorkerCertification::getBackImg, workerCertificationUpdateDTO.getBackImg())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationMaterial()), WorkerCertification::getCertificationMaterial, workerCertificationUpdateDTO.getCertificationMaterial())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationTime()), WorkerCertification::getCertificationTime, workerCertificationUpdateDTO.getCertificationTime());
        super.update(updateWrapper);
    }

    //提交认证申请
    @Override
    public WorkerCertification certification(WorkerCertificationAuditAddReqDTO workerCertificationAuditAddReqDTO) {
        WorkerCertification workerCertification = BeanUtil.toBean(workerCertificationAuditAddReqDTO, WorkerCertification.class);
        //保存到worker_certification表
        workerCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        workerCertification.setCertificationTime(LocalDateTime.now());
        workerCertification.setId(UserContext.getCurrentUser().getId());
        this.save(workerCertification);
        //保存到worker_certification_audit表
        WorkerCertificationAudit workerCertificationAudit = BeanUtil.copyProperties(workerCertification, WorkerCertificationAudit.class, "id");
        workerCertificationAudit.setServeProviderId(UserContext.getCurrentUser().getId());
        workerCertificationAuditMapper.insert(workerCertificationAudit);

        return workerCertification;

    }

    //查询最新的驳回原因
    @Override
    public String rejectReason() {
        try {
            // 1. 从ThreadLocal中获取当前用户ID（服务人员ID）
            Long serveProviderId = UserContext.currentUserId();
            if (serveProviderId == null) {
                log.warn("未获取到服务人员ID，返回空驳回原因");
                return "";
            }

            // 2. 查询最新的被驳回的认证记录
            // 修正查询条件：只需要查询认证失败的记录，审核状态可能为1（已审核）或者不需要限制
            WorkerCertificationAudit workerCertificationAudit = workerCertificationAuditMapper.selectOne(
                    Wrappers.<WorkerCertificationAudit>lambdaQuery()
                            .eq(WorkerCertificationAudit::getServeProviderId, serveProviderId)
                            .eq(WorkerCertificationAudit::getCertificationStatus, CertificationStatusEnum.FAIL.getStatus())
                            .isNotNull(WorkerCertificationAudit::getRejectReason) // 确保驳回原因不为空
                            .ne(WorkerCertificationAudit::getRejectReason, "")    // 确保驳回原因不是空字符串
                            .orderByDesc(WorkerCertificationAudit::getAuditTime)  // 按审核时间倒序
                            .last("limit 1")
            );

            workerCertificationAuditMapper.insert(workerCertificationAudit);
            // 3. 返回驳回原因，如果为空返回空字符串
            return workerCertificationAudit != null && workerCertificationAudit.getRejectReason() != null
                    ? workerCertificationAudit.getRejectReason().trim()
                    : "";

        } catch (Exception e) {
            log.error("查询驳回原因异常，用户ID: {}, 异常信息: {}");
            return "";
        }
    }

    @Override
    public PageResult<WorkerCertificationAuditResDTO> pageQueryWorkerCertificationList(WorkerCertificationAuditPageQueryReqDTO workerCertificationAuditPageQueryReqDTO) {
        return PageHelperUtils.selectPage(workerCertificationAuditPageQueryReqDTO, () -> baseMapper.pageQueryWorkerCertificationList(workerCertificationAuditPageQueryReqDTO));
    }


    @Transactional
    @Override
    public void audit(Long id, Integer certificationStatus, String rejectReason) {

//这个id传的应该是是WorkerCertificationAudit的主键
        //       一. 修改worker_certification_audit表
//        审核状态1为已经审核
// 直接更新，不需要先查询
        LambdaUpdateWrapper<WorkerCertificationAudit> auditLambdaUpdateWrapper =
                Wrappers.<WorkerCertificationAudit>lambdaUpdate()
                        .eq(WorkerCertificationAudit::getId, id)
                        .set(WorkerCertificationAudit::getCertificationStatus, certificationStatus)
                        .set(WorkerCertificationAudit::getRejectReason, rejectReason)
                        .set(WorkerCertificationAudit::getAuditTime, LocalDateTime.now())  // 修正：使用当前时间
                        .set(WorkerCertificationAudit::getAuditStatus, 1)
                        .set(WorkerCertificationAudit::getAuditorId, UserContext.currentUserId())            // 修正：传入审核人ID
                        .set(WorkerCertificationAudit::getAuditorName, UserContext.currentUser().getName());       // 修正：传入审核人姓名

        int updateCount = workerCertificationAuditMapper.update(null, auditLambdaUpdateWrapper);

// 如果需要检查是否更新成功
        if (updateCount == 0) {
            throw new RuntimeException("更新失败，记录不存在或已被删除");
        }


//        二.修改worker_certification表
        //1.更新worker_certification表


        LambdaUpdateWrapper<WorkerCertification> updateWrapper = Wrappers.<WorkerCertification>lambdaUpdate()
                .eq(WorkerCertification::getId, workerCertificationAuditMapper.selectById(id).getServeProviderId()).set(WorkerCertification::getCertificationStatus, certificationStatus);
//        因为建表语句设置了当前时间，可以不用考虑，不行后面再加
//                .set(WorkerCertification::getUpdateTime, LocalDateTime.now());

        if (certificationStatus == 2) {
            updateWrapper = updateWrapper.set(WorkerCertification::getCertificationTime, LocalDateTime.now());
        }
        this.update(updateWrapper);


    }
}
